<template>
    <el-drawer title="我是标题" :visible.sync="dialogVisible" :close-on-press-escape="false" :wrapperClosable="false" :with-header="false" size='960px' class="demand_box" @close="resetForm('addMtVedioForm')">
        <AddInfo ref="AddInfo"/>
        <AddInfoBulk ref="AddInfoBulk"/>
        <div class="flexbox flexcolumn height_100">
            <div class="demand_head flexbox flexcenter flexbetween">
                <span class="demand_title">上传素材</span>
                <span class="icon_btn icon_btn_32"><img src="../../../assets/img/close_check.svg" alt="" @click="resetForm('addMtVedioForm')"></span>
            </div>
            <div class="demand_center flex">
                <!-- <el-upload
                    drag
                    action="a"
                    :on-change="ReadFileMD5"
                    :http-request="UploadSceneModel"
                    :auto-upload="false"
                    multiple
                >
                <i class="el-icon-upload" />
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload> -->
                <el-form label-position="top" style="margin-top:-10px" :model="addMtVedioForm" size="medium" :hide-required-asterisk='true' ref="addMtVedioForm" :rules="addMtVedioRules" class="dialog_form">
                    <el-form-item label="" prop="">
                        <el-upload class="video_loader" ref="upload" drag :show-file-list="false" accept=".mp4,.MP4,.MOV,.mov" :http-request="videoUploadRequest" multiple  :on-change="handleChange" :before-upload="beforeVideoUpload">
                            <div class="pot_content flexbox flexcenter">
                                <img src="../../../assets/img/pot_video.svg" alt="">
                                <span class="pot_text">点击上传 或直接将视频文件拖入此区域</span>
                                <span class="pot_tips">视频大小不超过 1GB，视频格式为 MP4 MOV</span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div class="has_load_title flexbox flexcenter flexbetween">
                    <span class="font_16 color_01">上传列表</span>
                    <!-- <el-button class="plain_blue" icon="el-icon-circle-plus-outline" size="small" :disabled="move_loading" @click="addInfoBulk">批量设置名称</el-button> -->
                </div>
                <div class="operate_upvideo flexbox flexcenter flexbetween" v-if="multipleSelection.length > 0">
                    <div class="flexbox flexcenter">
                        <span >已选<span style="color:#165DFF"> {{multipleSelection.length}} </span>项</span>
                        <div class="flexbox operate_btn">
                            <div @click="addInfoBulk">设置名称</div>
                            <div @click="multipleTag">素材标签</div>
                            <!-- <div @click="multipleProductTag">产品标签</div> -->
                            <div @click="multipledelet">移除</div>
                        </div>
                    </div>
                    <div @click="cleanSelection">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M17.2543 8.25451C17.6708 7.83795 17.6708 7.16257 17.2543 6.74601C16.8377 6.32945 16.1623 6.32945 15.7458 6.74601L12 10.4918L8.25426 6.74601C7.8377 6.32945 7.16233 6.32945 6.74577 6.74601C6.32921 7.16257 6.32921 7.83795 6.74577 8.25451L10.4915 12.0003L6.74577 15.746C6.32921 16.1626 6.32921 16.8379 6.74577 17.2545C7.16233 17.6711 7.8377 17.6711 8.25426 17.2545L12 13.5088L15.7458 17.2545C16.1623 17.6711 16.8377 17.6711 17.2543 17.2545C17.6708 16.8379 17.6708 16.1626 17.2543 15.746L13.5085 12.0003L17.2543 8.25451Z" fill="#ACB2BB"/></svg>
                    </div>
                </div>
                <el-table :data="tableData" class="com_table" :cell-class-name="cellClassName"  @cell-click="openTag" @selection-change="handleSelectionChange" ref="multipleTable" style="margin-top:12px">
                    <div slot="empty" class="flexbox flexcenter flexcolumn flexjust" style="height:300px">
                        <img src="../../../assets/img/null_icon.svg" alt="">
                        <div class="font_13 color_03">暂无数据</div>
                    </div>
                     <el-table-column type="selection" width="55" :selectable="checkselec"></el-table-column>
                    <el-table-column prop="full_name" label="素材">
                        <template slot-scope="scope">
                            <div class="flexbox flexcenter">
                                <div class="vd_left" style="cursor: pointer;">
                                    <el-popover placement="left" title="" width="280" trigger="hover" @show="playVd('videodiloag'+scope.$index)" @hide="pausevideo('videodiloag'+scope.$index)" open-delay="500" close-delay="100" content="" v-if="scope.row.material">
                                        <div style="width:100%;height:500px">
                                            <video :ref="'videodiloag'+scope.$index" muted autoplay controls width="100%" height="100%" :src="scope.row.material" type="video/mp4">
                                                <!-- <source :src="scope.row.material" type="video/mp4">  -->
                                            </video>
                                        </div>
                                         <video :src="scope.row.material"  slot="reference" class="vd_poster"></video>
                                         <!-- <video :src="scope.row.material"  slot="reference" class="vd_poster"  @click="playVideo(scope.row.material)"></video> -->
                                    </el-popover>
                                    <img src="../../../assets/img/no_img.png" alt="" class="vd_poster" v-else>
                                    <!-- <el-image  alt="" v-if="scope.row.material" :src="scope.row.material"></el-image> -->
                                    <!-- <el-image  class="vd_poster"  v-if="scope.row.material" :src="scope.row.material+'&x-oss-process=video/snapshot,t_0,f_jpg'" :preview-src-list="[scope.row.material+'&x-oss-process=video/snapshot,t_0,f_jpg']"></el-image> -->
                                    <!-- <img src="../../../assets/img/no_img.png" alt="" class="vd_poster" v-else> -->
                                </div>

                                <div class="vd_center flex">
                                    <!-- <template v-if="scope.row.material==''">
                                        <el-link :underline="false" type="danger">原文件名:</el-link>{{scope.row.material_name}}
                                    </template>
                                    <template v-else>
                                        <el-link :underline="false" type="primary">新素材名:</el-link>{{scope.row.material_name}}
                                    </template> -->
                                    <template  v-if="!scope.row.uploadUrlName">
                                        <el-link :underline="false" type="danger">原文件名:</el-link>{{scope.row.material_name}}
                                    </template>
                                    <template v-else>
                                        <el-link :underline="false" type="primary">新文件名:</el-link>{{scope.row.material_name}}
                                    </template>
                                    <!-- <div class="no_name flexbox flexcenter" @click="addMtInfo(scope.row,scope.$index)" v-else>
                                        生成名称
                                        <img src="../../assets/img/no_name.png" style="margin-left:2px;margin-top:-1px" alt="">
                                    </div> -->
                                </div>
                                <div class="vd_right">
                                    <el-link type="primary" :disabled="move_loading" :underline="false" @click="addInfo(scope.row,scope.$index)"><img src="@/assets/img/edit_icon4.svg" alt="" srcset=""></el-link>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tag" label="素材标签" width="188">
                        <template slot-scope="scope">
                            <div v-if="scope.row.tag_id.length > 0" class="flexbox flexcenter cell_edit" style="gap:4px">
                                <div  style="cursor: pointer;">
                                    <span v-for="(item,index) in scope.row.tag_id">{{item.name}} <span v-if="index+1 != scope.row.tag_id.length">、</span></span>
                                </div>
                                <div class="hover_edit"><img src="@/assets/img/edit_icon4.svg" alt="" srcset=""></div>
                            </div>
                            <div v-else class="cell_edit flexbox flexcenter">
                                <span>--</span> 
                                <!-- <div class="hover_edit"><img src="@/assets/img/edit_icon4.svg" alt="" srcset=""></div> -->
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="producttag" label="产品标签" width="188">
                        <template slot-scope="scope">
                            <div v-if="scope.row.product_tag_id.length > 0" class="flexbox flexcenter cell_edit" style="gap:4px">
                                <div  style="cursor: pointer;">
                                    <span v-for="(item,index) in scope.row.product_tag_id">{{item.name}} <span v-if="index+1 != scope.row.product_tag_id.length">、</span></span>
                                </div>
                                <div class="hover_edit"><img src="@/assets/img/edit_icon4.svg" alt="" srcset=""></div>
                            </div>
                            <div v-else class="">
                                <span>--</span> 
                                 <!-- <div class="hover_edit"><img src="@/assets/img/edit_icon4.svg" alt="" srcset=""></div> -->
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="product_num" label="进度" width="134">
                        <template slot-scope="scope">
                            <span class="font_14 color_02" v-if="scope.row.process==0">等待上传,请先设置名称</span>
                            <span class="font_14 color_02" v-else-if="scope.row.process==1">设置已完成，等待上传</span>
                            <span class="text_red" v-else-if="scope.row.process==99999">素材库已存在相同视频，无法上传</span>
                            <div v-else>
                                <el-progress :percentage="scope.row.process" :stroke-width="10"></el-progress>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="product_num" label="操作" width="80">
                        <template slot-scope="scope">
                            <el-link type="danger" :underline="false" :disabled="move_loading" @click="deletTable(scope.$index)">移除</el-link>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="demand_footer flexbox flexcenter">
                <el-button plain size="small" class="el-button-width" @click="resetForm()">取 消</el-button>
                <el-button type="primary" size="small" class="el-button-width" @click="submitForm()" :loading="loading" :disabled='loading'>立即上传</el-button>
            </div>
        </div>
        <PlayVideo/>
        <LabelSettingDialog :taglist="tag_list" ModuleName="fenjinUpload" ref="labelsettingbulk" />
        <LabelSettingDialog :taglist="tag_list" ModuleName="Storyboard2" ref="labelsetting" />
        <LabelDialog 
            ref="labelporduct" 
            ReqUrl="/adminapi/Materialfj/tagAdd" 
            :taglist="Typetaglist" 
            TagType="3" 
            :ProductId="productSelectId" 
            @getTagList="(query)=>{getNewTagList(query,3)}"
            @submitForm="submitDataForm"/>
    </el-drawer>
</template>

<script>
import AddInfo from "./AddInfo";
import AddInfoBulk from "./AddInfoBulk";
import LabelSettingDialog from "@/components/LabelSettings/index";
import LabelDialog from "@/components/components/LabelDialog";
import PlayVideo from "@/components/material/PlayVideo";
import { clientInfo,clientTos,tosLink } from "../../../assets/js/oss";
import SparkMD5 from "spark-md5";
export default {
    name: "",
    data() {
        return {
            multipleSelection:[],
            loading: false,
            dialogVisible: false,
            move_loading: false,
            tableData: [],
            cptableData:[],
            AddNum:0,
            addMtVedioRules: {},
            nameArr:[],
            residue:{},
            tag_list:[],
            Typetaglist:[],
            selectTagIndex:0,
            selectProductTagIndex:0,
            productSelectId:""
        };
    },
    created() {
        this.$bus.on("addVedio", (value) => {
            this.dialogVisible = value.dialogVsb;
        });
    },
    beforeDestroy() {
        this.$bus.off("addVedio");
    },
    methods: {
        submitDataForm(addMtInfoForm){
            this.$refs.labelporduct.closeDialog();
            this.$refs.labelporduct.loading = false;
            this.tableData[this.selectTagIndex].product_tag_id = JSON.parse(JSON.stringify(addMtInfoForm))
        },
        GettagData(data){
            this.tableData[this.selectTagIndex].tag_id = JSON.parse(JSON.stringify(data))
        },
        cellClassName({row, column, rowIndex, columnIndex}){
            row.index = rowIndex;
            column.index = columnIndex;
        },
       async openTag(row, column, cell, event){
        // console.log(row.index)
            // 素材标签
            if(column.property == "tag"){
                this.selectTagIndex = row.index;
                await this.getTagList();
                this.$nextTick(()=>{
                    this.$refs.labelsetting.openDialog();
                    this.$refs.labelsetting.selectTag(this.tag_list[0]) 
                    this.$refs.labelsetting.tagpid = JSON.parse(JSON.stringify(row.tag_id))
                })
            }
            // 产品标签
            if(column.property == "producttag" && row.productSelect.id){
                this.productSelectId = row.productSelect.id;
                this.selectProductTagIndex = row.index;
                await this.getNewTagList(undefined,3);
                    this.$nextTick(()=>{
                        this.$refs.labelporduct.openDialog();
                        this.$refs.labelporduct.selectTag(this.Typetaglist[0]) 
                        this.$refs.labelporduct.tagpid = JSON.parse(JSON.stringify(row.product_tag_id))
                    })
            }
        },
        playVd(index){
            console.log( this.$refs[index].url)
            this.$refs[index].play();
        },
        pausevideo(index){
            this.$refs[index].pause();
        },
        playVideo(url) {
            const attr = {
                dialogVsb: true,
                url: url,
            };
            this.$bus.emit("playVideo", attr);
        },
        // 获取标签
    async getTagList(query) {
            const { data: res } = await this.$http.post(
                "adminapi/materialfj/tagList",
                {
                    page: 1,
                    limit: 0,
                    query:query?query:undefined,
                    tag_type:1
                }
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
              this.tag_list = res.data.list;
            }
        },
    async getNewTagList(query,tag_type) {
            const { data: res } = await this.$http.post(
                "adminapi/materialfj/tagList",
                {
                    page: 1,
                    limit: 0,
                    query:query?query:undefined,
                    tag_type:tag_type,
                    product_id:this.productSelectId?this.productSelectId:undefined
                }
            );
            if (res.code !== 200) {
                this.$message.error(res.msg);
                return;
            } else {
              this.Typetaglist = res.data.list;
            }
        },
         // 添加标签
    // addMaterialTag(item, type) {
     
    // },
        checkselec(row){
            return !this.loading;
        },
      async  multipleTag(){
            await this.getTagList();
            this.$nextTick(()=>{
                this.$refs.labelsettingbulk.openDialog();
                this.$refs.labelsettingbulk.selectTag(this.tag_list[0]) 
            })
        },
    // async multipleProductTag(){
    //       await this.getNewTagList(undefined,3);
    //         this.$nextTick(()=>{
    //             this.$refs.labelporduct.openDialog();
    //             this.$refs.labelporduct.selectTag(this.Type_tag_list[0]) 
    //         })
    // },
        multipledelet(){
            if(this.loading)return;
            this.multipleSelection.forEach(e=>{
                this.tableData.forEach((s,index) =>{
                    if(e.material_md5 == s.material_md5){
                        this.tableData.splice(index, 1)
                        this.cptableData.splice(index, 1)
                        this.AddNum = --this.AddNum
                    }
                })
                
            })
            ;
            this.residue = {};
        },
        handleSelectionChange(val){
            this.multipleSelection = val;
        },
        cleanSelection(){
            if(this.loading)return;
            this.$refs.multipleTable.clearSelection();
        },
        
        // 提交
        async submitForm() {
            if (this.tableData.length == 0) {
                this.$message.error("请先选择视频");
                return;
            }
            for (let i in this.tableData) {
                if (!this.tableData[i].brand_id) {
                    this.$message.error("请完善视频信息");
                    return;
                }
            }
            let videoVerify = [];
            const { data: req } = await this.$http.post("/adminapi/Materialfj/videoVerify",{ md5: this.tableData.map(e => e.material_md5) });
            if (req.code !== 200) {
                for (let i in this.tableData) {
                    for (let ii in req.data) {
                        if (this.tableData[i].material_md5 == req.data[ii].material_md5) {
                            videoVerify.push(i)
                        }
                    }
                }
                let arr = req.data.map(e=>e.material_name).join('----')
                    this.$message.error('存在重复视频，请处理,'+arr);
                // return;
            } 
            this.loading = true;
            let list = [];
            const that = this;
            const client = clientInfo;
            const clienttos = clientTos
                for (let i in this.tableData) {
                    console.log(this.tableData[i].material,'******************')
                    if(this.tableData[i].material.split('?').length == 1){
                        if(!videoVerify.includes(i)){
                            try {
                                // const ret = await clienttos.putObject({
                                // key: that.tableData[i].uploadUrlName,
                                // body: that.tableData[i].file,
                                // progress: (p, cpt) => {
                                //         that.tableData[i].process = Math.floor(p * 100);
                                // },
                                //     });
                                 // 分片大小最小为 5MB
                                const partSize = 10 * 1024 * 1024;

                                const ret = await clienttos.uploadFile({
                                    key: that.tableData[i].uploadUrlName,
                                    file: that.tableData[i].file,
                                    // 上传时指定分片大小
                                    partSize,
                                    // 分片并发数，默认为1
                                    taskNum: 10,
                                    progress: (p, cpt) => {
                                     that.tableData[i].process = Math.floor(p * 100);
                                    },
                                });
                                console.log(ret)
                                    if (ret.statusCode === 200) {
                                        let url = tosLink + that.tableData[i].uploadUrlName
                                        let timestamp = new Date().getTime();
                                        let vdUrl = url + "?v=" + timestamp;
                                        that.tableData[i].material = vdUrl;
                                    } else {
                                        that.$message.error("TOS上传失败！状态码：" + ret.statusCode);
                                    }
                            } catch (error) {
                                console.log(error)
                                this.loading = false;
                                this.move_loading = false;
                                this.$message.error("TOS上传失败！");
                            }
                        }else{
                            that.tableData[i].process = 99999;
                        }
                    }
                }
            for (let i in that.tableData) {
                console.log(that.tableData)
               let photographerUid = that.tableData[i].photographer_uid.map(e=>e)
             if (that.tableData[i].material && that.tableData[i].material.startsWith('blob:') ||  !that.tableData[i].material) {
                    const now = new Date();
                    const seconds = now.getSeconds().toString().padStart(2, '0');
                    that.loading = false;
                    that.move_loading = false;
                    videoVerify.push(i)
                    if(that.tableData[i].process != 99999){
                        that.tableData[i].process = 0;
                    }
                    setTimeout(() => {
                        that.$message.error(`${that.tableData[i].material_name}部分视频上传失败！请重新上传`);
                    },seconds);
                    console.log(`对象中的 name 是无效的: 'null/undefined/empty'`);  
                } else {
                    list.push({
                        brand_id: this.tableData[i].brand_id,
                        brand_name: this.tableData[i].brand_name,
                        duration: this.tableData[i].duration,
                        file_format: this.tableData[i].file_format,
                        height: this.tableData[i].height,
                        material: this.tableData[i].material,
                        material_md5: this.tableData[i].material_md5,
                        material_name: this.tableData[i].material_name,
                        photographer_uid: photographerUid.includes(9999)?[]:photographerUid,
                        primary_name: this.tableData[i].primary_name,
                        product_id: this.tableData[i].product_id,
                        product_name: this.tableData[i].product_name,
                        sch_id: this.tableData[i].sch_id,
                        tag_id: this.tableData[i].tag_id.map(e=> e.id),
                        product_tag_id: this.tableData[i].product_tag_id.map(e=> e.id),
                        brand_tag_id:[],
                        width: this.tableData[i].width,
                        defined_name: this.tableData[i].defined_name,
                    });
                }
            }
        //    let datacp  = list.map((e,i)=>{
        //         if(!videoVerify.includes(i+'')){
        //             return e
        //         }
        //     }).filter(e=>e)
            if(list.length>0){
                const { data: res } = await this.$http.post(
                "/adminapi/materialfj/materialUpload",
                {
                    list: list,
                }
                );
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    this.loading = false;
                    return;
                } else {
                
                if(videoVerify.length == 0){
                    this.resetForm();
                }else{
                    this.tableData = this.tableData.map((e,i)=>{
                        if(videoVerify.includes(i+'')){
                            return e
                        }
                    }).filter(e=>e)
                }
                this.$message({
                    message: "创建成功",
                    type: "success",
                });
                this.$parent.getMaterialList(1);
             }
            }
            this.loading = false;
        },

        beforeVideoUpload(file) {
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "MP4" || testmsg === "mp4" || testmsg === "MOV" || testmsg === "mov";
            const isLt2M = file.size / 1024 / 1024 < 1000;
            if (!extension) {
                this.$message({
                    message: "上传视频只能是mp4、MOV/ MP4、MOV格式!",
                    type: "error",
                });
                return false;
            }
            if (!isLt2M) {
                this.$message({
                    message: "上传文件大小不能超过 1GB!",
                    type: "error",
                });
                return false;
            }

            return extension || isLt2M;
        },
       async videoUploadRequest(file) {
            let that = this;
            let is_repeat = that.cptableData.some((item) => {
                if (item.material_name == file.file.name) {
                    return true;
                }
            });
                
                    if (!is_repeat) {
                        let videoType = {
                            quicktime:'mov',
                            mp4:'mp4'
                        }
                    that.cptableData.push({
                            file: file.file,
                            brand_id: "",//品牌ID
                            brand_name: "",//品牌名称
                            duration: "",
                            file_format: videoType[file.file.type.split("/")[1]],
                            material: "",
                            material_md5: "",
                            material_name: file.file.name,
                            photographer_uid: [],
                            primary_name: file.file.name.slice(0,-4),
                            product_id: "",
                            product_name: "",
                            defined_name:"",
                            sch_id: [],
                            tag_id: [],
                            width: "",
                            height:"",
                            process: 0,
                            brandSelect: {},
                            productSelect: {},
                        });
                    }
            
            // let that = this;
            let videoSrc = URL.createObjectURL(file.file);
            let videoElement = document.createElement("video");
            videoElement.src = videoSrc;
            videoElement.addEventListener("loadedmetadata", function (v) {
                // URL.revokeObjectURL(videoSrc);
                // let sizeVal =
                //     videoElement.videoWidth / videoElement.videoHeight ==
                //         16 / 9 ||
                //     videoElement.videoWidth / videoElement.videoHeight ==
                //         9 / 16;
                // if (Math.round(videoElement.duration) <= 4) {
                //     that.$message.error("视频时长不能少于4s");
                //     return;
                // }
                // if (!sizeVal) {
                //     that.$message.error("视频尺寸比例不正确");
                //     return;
                // }
                // if (that.tableData.length >= 20) {
                //     return;
                // }

                //md5方法2
                
                let fileReader = new FileReader();
                let dataFile = file.file;
                let spark = new SparkMD5();
                fileReader.readAsBinaryString(dataFile);
                fileReader.onload = function (e) {
                    spark.appendBinary(e.target.result);
                    let md5 = spark.end();
                    let is_repeat = that.tableData.some((item,index) => {
                        if (item.material_md5 == md5) {
                            that.cptableData.forEach((data,dataIndex) =>{
                                if(data.material_name == file.file.name){
                                    that.cptableData.splice(dataIndex,1)
                                }
                            })
                            // console.log(file.file.name,that.cptableData)
                            return true;
                        }
                    });

                    if (is_repeat) {
                        that.$message.error("视频已选择，请勿重复上传");
                        return;
                    } else {
                        let videoType = {
                            quicktime:'mov',
                            mp4:'mp4'
                        }   
                            // console.log(videoElement.src)
                            //     that.tableData.push(that.cptableData[that.AddNum]);
                            //     that.AddNum = ++that.AddNum;
                            //     that.residue[file.file.name] = {
                            //             duration: Math.round(videoElement.duration),
                            //             width :videoElement.videoWidth,
                            //             height :videoElement.videoHeight,
                            //             material_md5 : md5,
                            //             material:videoElement.src
                            //     }
                            //     for(let ii = 0; ii < that.tableData.length; ii++){
                            //         if(Object.keys(that.residue).length>0){
                            //            if(that.residue[that.tableData[ii].material_name]){
                            //                 that.tableData[ii].duration = that.residue[that.tableData[ii].material_name].duration
                            //                 that.tableData[ii].width = that.residue[that.tableData[ii].material_name].width
                            //                 that.tableData[ii].height = that.residue[that.tableData[ii].material_name].height
                            //                 that.tableData[ii].material_md5 = that.residue[that.tableData[ii].material_name].material_md5
                            //                 that.tableData[ii].material = that.residue[that.tableData[ii].material_name].material
                            //            }
                            //         }
                            //     }
                        that.tableData.push({
                            file: file.file,
                            brand_id: "",//品牌ID
                            brand_name: "",//品牌名称
                            duration: Math.round(videoElement.duration),
                            file_format: videoType[file.file.type.split("/")[1]],
                            material: videoElement.src,
                            material_md5: md5,
                            material_name: file.file.name,
                            photographer_uid: [],
                            primary_name: file.file.name.slice(0,-4),
                            product_id: "",
                            product_name: "",
                            defined_name:"",
                            sch_id: [],
                            product_tag_id:[],
                            tag_id: [{"id": 125,"pid": 123,"name": "竖屏"},{id: 119,name: "一级展示（随拍&摆拍)（上传默认）",pid: 84}],
                            width: videoElement.videoWidth,
                            height:videoElement.videoHeight,
                            process: 0,
                            brandSelect: {},
                            productSelect: {},
                        });
                            console.log(videoElement.src,that.tableData)

                        if(that.cptableData.length == that.tableData.length){
                            console.log(that.cptableData.length,that.tableData.length,'**********************************')
                            let idIndexMap = new Map(that.cptableData.map((item, index) => [item.material_name, index]));  
      
                            // 使用sort方法和自定义比较函数来重新排序obtainedOrder  
                            that.tableData.sort((a, b) => {
                            // 获取a和b的id在originalOrder中的索引  
                            let indexA = idIndexMap.get(a.material_name);  
                            let indexB = idIndexMap.get(b.material_name);  
                            
                            // 根据索引进行排序  
                            return indexA - indexB;  
                            });  
                        }
                        
                    }
                    that.$refs.upload.clearFiles();
                };
            });
        },

        //移除列表
        deletTable(index) {
            this.tableData.splice(index, 1);
            this.cptableData.splice(index, 1);
            this.AddNum = --this.AddNum;
            this.residue = {};
        },

        async uploadSingle(option, name, index) {
            // console.log(this.tableData,'----------------------------')
            const that = this;
            this.move_loading = true;
            this.loading = true;
            let file = option;
            let nowData = new Date();
            let year = nowData.getFullYear();
            let month =
                nowData.getMonth() + 1 < 10
                    ? "0" + (nowData.getMonth() + 1)
                    : nowData.getMonth() + 1;
            let date =
                nowData.getDate() < 10
                    ? "0" + nowData.getDate()
                    : nowData.getDate();
            let getData = year + "-" + month + "-" + date;
            let videoType = {
                        quicktime:'.mov',
                        mp4:'.mp4'
                    }
            let relativePath = "fenjing/" + getData + "/";
            let fileName = name + videoType[file.type.split("/")[1]];
            this.tableData[index].uploadUrlName = relativePath + fileName;
            this.tableData[index].file = file;
            // try {
            //     const client = clientInfo;
            //     const clienttos = clientTos
            //     let file = option;
            //     let nowData = new Date();
            //     let year = nowData.getFullYear();
            //     let month =
            //         nowData.getMonth() + 1 < 10
            //             ? "0" + (nowData.getMonth() + 1)
            //             : nowData.getMonth() + 1;
            //     let date =
            //         nowData.getDate() < 10
            //             ? "0" + nowData.getDate()
            //             : nowData.getDate();
            //     let getData = year + "-" + month + "-" + date;
            //     let videoType = {
            //                 quicktime:'.mov',
            //                 mp4:'.mp4'
            //             }
            //     let relativePath = "fenjing/" + getData + "/";
            //     let fileName = name + videoType[file.type.split("/")[1]];
            //     const ret = await clienttos.putObject({
            //         key: relativePath + fileName,
            //         body: file,
            //         progress: (p, cpt) => {
            //             that.tableData[index].process = Math.floor(p * 100);
            //         },
            //     });
            //     if (ret.statusCode === 200) {
            //         let url = tosLink+relativePath + encodeURIComponent(fileName)
            //         var timestamp = new Date().getTime();
            //         let vdUrl = url + "?v=" + timestamp;
            //         this.tableData[index].material = vdUrl;
            //         this.move_loading = false;
            //         this.loading = false;
            //     } else {
            //         this.loading = false;
            //         this.move_loading = false;
            //         this.$message.error("上传失败！");
            //     }
            //     // let ret = await client.multipartUpload(
            //     //     relativePath + fileName,
            //     //     file,
            //     //     {
            //     //         progress: function (p) {
            //     //             that.tableData[index].process = Math.floor(p * 100);
            //     //         },
            //     //     }
            //     // );
            //     // if (ret.res.statusCode === 200) {
            //     //     let url = ret.res.requestUrls[0];
            //     //     let urlstr = url.substring(0, url.lastIndexOf("?"));
            //     //     var timestamp = new Date().getTime();
            //     //     let vdUrl = urlstr + "?v=" + timestamp;
            //     //     this.tableData[index].material = vdUrl;
            //     //     this.move_loading = false;
            //     //     this.loading = false;
            //     // } else {
            //     //     this.loading = false;
            //     //     this.move_loading = false;
            //     //     this.$message.error("上传失败！");
            //     // }
            // } catch (error) {
            //     console.log(error)
            //     this.loading = false;
            //     this.move_loading = false;
            //     this.$message.error("上传失败！");
            // }
            this.move_loading = false;
            this.loading = false;
        },
        //不修改数据 批量修改标签跟需求id
        uploadMultiTagandschId(tag,sch){
             const multipleSelection = this.multipleSelection.map(e=>e.material_md5);
            const SelectTabke = this.tableData.map((e,index)=>{
                    if(multipleSelection.includes(e.material_md5)){
                        return index;
                    }}
            ).filter(item => item === 0 || Boolean(item));
            for (let [i, v] of SelectTabke.entries()) {
                this.tableData[v].sch_id= sch;
                this.tableData[v].tag_id= tag;
            }
        },
        uploadTagandschId(tag,sch,index){
            this.tableData[index].sch_id= sch;
            this.tableData[index].tag_id= tag;
        },
        // 批量上传
        async uploadMulti(name, info) {
            // console.log(this.tableData,'***************')
            const multipleSelection = this.multipleSelection.map(e=>e.material_md5);
            const SelectTabke = this.tableData.map((e,index)=>{
                    if(multipleSelection.includes(e.material_md5)){
                        return index;
                    }}
            ).filter(item => item === 0 || Boolean(item));

            for (let [i, v] of SelectTabke.entries()) {
                this.move_loading = true;
                this.loading = true;
                        this.tableData[v].brand_id = info.brand_id;
                        this.tableData[v].brand_name= info.brand_name;
                        this.tableData[v].material_name= name[i];
                        this.tableData[v].photographer_uid= info.photographer_uid;
                        this.tableData[v].product_id= info.product_id;
                        this.tableData[v].product_name= info.product_name;
                        this.tableData[v].defined_name= info.defined_name;
                        this.tableData[v].sch_id= info.sch_id;
                        this.tableData[v].tag_id= info.tag_id;
                        this.tableData[v].brand_tag_id = [];
                        this.tableData[v].product_tag_id = info.product_tag_id;
                        this.tableData[v].brandSelect = info.brandSelect;
                        this.tableData[v].productSelect = info.productSelect;
                        this.tableData[v].process = info.process;

                        let file = this.tableData[v].file;
                        let nowData = new Date();
                        let year = nowData.getFullYear();
                        let month =
                            nowData.getMonth() + 1 < 10
                                ? "0" + (nowData.getMonth() + 1)
                                : nowData.getMonth() + 1;
                        let date =
                            nowData.getDate() < 10
                                ? "0" + nowData.getDate()
                                : nowData.getDate();
                        let getData = year + "-" + month + "-" + date;
                        let videoType = {
                                    quicktime:'.mov',
                                    mp4:'.mp4'
                                }
                        let relativePath = "fenjing/" + getData + "/";
                        let fileName = name[i] + videoType[this.tableData[v].file.type.split("/")[1]];
                        this.tableData[v].uploadUrlName = relativePath + fileName;
                        this.tableData[v].file = file;
                        
                // const that = this;
                // try {
                //     const client = clientInfo;
                //     const clienttos = clientTos
                //     let file = this.tableData[v].file;
                //     let nowData = new Date();
                //     let year = nowData.getFullYear();
                //     let month =
                //         nowData.getMonth() + 1 < 10
                //             ? "0" + (nowData.getMonth() + 1)
                //             : nowData.getMonth() + 1;
                //     let date =
                //         nowData.getDate() < 10
                //             ? "0" + nowData.getDate()
                //             : nowData.getDate();
                //     let getData = year + "-" + month + "-" + date;
                //     let videoType = {
                //             quicktime:'.mov',
                //             mp4:'.mp4'
                //         }
                //     let relativePath = "fenjing/" + getData + "/";
                //     let fileName = name[i] + videoType[this.tableData[v].file.type.split("/")[1]];
                //     const ret = await clienttos.putObject({
                //         key: relativePath + fileName,
                //         body: file,
                //         progress: (p, cpt) => {
                //             that.tableData[v].process = Math.floor(p * 100);
                //         },
                //     });
                //     if (ret.statusCode === 200) {
                //         let url = tosLink+relativePath + encodeURIComponent(fileName)
                //         let urlstr = url.substring(0, url.lastIndexOf("?"));
                //         var timestamp = new Date().getTime();
                //         let vdUrl = url + "?v=" + timestamp;
                //         this.tableData[v].material = vdUrl;
                //         this.loading = false;
                //         this.move_loading = false;
                //     } else {
                //         this.loading = false;
                //         this.move_loading = false;
                //         this.$message.error("上传失败！");
                //     }
                //     // let ret = await client.multipartUpload(
                //     //     relativePath + fileName,
                //     //     file,
                //     //     {
                //     //         progress: function (p) {
                //     //             that.tableData[i].process = Math.floor(p * 100);
                //     //         },
                //     //     }
                //     // );
                //     // if (ret.res.statusCode === 200) {
                //     //     let url = ret.res.requestUrls[0];
                //     //     let urlstr = url.substring(0, url.lastIndexOf("?"));
                //     //     var timestamp = new Date().getTime();
                //     //     let vdUrl = urlstr + "?v=" + timestamp;
                //     //     this.tableData[i].material = vdUrl;
                //     //     this.loading = false;
                //     //     this.move_loading = false;
                //     // } else {
                //     //     this.loading = false;
                //     //     this.move_loading = false;
                //     //     this.$message.error("上传失败！");
                //     // }
                // } catch (error) {
                //     this.loading = false;
                //     this.move_loading = false;
                //     this.$message.error("上传失败！");
                // }
            }
            this.loading = false;
            this.move_loading = false;
        },

        // 设置名称
        addInfo(row, index) {
            let copy = JSON.parse(JSON.stringify(row))
            const attr = {
                dialogVsb: true,
                index: index,
                info: {...copy,file:row.file},
            };
            this.$bus.emit("addInfo", attr);
        },

        // 批量设置名称
        addInfoBulk() {
            if(this.loading)return;
            if (this.multipleSelection.length <= 0) {
                this.$message.error("请先选择视频");
                return;
            } else {
                const attr = {
                    dialogVsb: true,
                    quantity: this.multipleSelection.length,
                    tag_id:[{"id": 125,"pid": 123,"name": "竖屏"},{id: 119,name: "一级展示（随拍&摆拍)（上传默认）",pid: 84}]
                };
                this.$bus.emit("addInfoBulk", attr);
            }
        },

        // 关闭重置表单
        resetForm() {
            this.move_loading = false;
            this.loading = false;
            this.cptableData= [];
            this.AddNum = 0;
            this.residue = {};
            this.addMtVedioRules = {};
            this.tableData = [];
            this.cleanSelection();
            this.$refs.upload.clearFiles();
            this.dialogVisible = false;
            // 清除 批量设置的值
            this.$refs.AddInfoBulk.$refs['ruleForm'].resetFields();
            this.$refs.AddInfoBulk.addMtInfoForm.brandSelect = {};
            this.$refs.AddInfoBulk.addMtInfoForm.productSelect = {};
        },
    },
    components: {
        AddInfo,
        AddInfoBulk,
        LabelSettingDialog,
        PlayVideo,
        LabelDialog
    },
};
</script>

<style scoped>
.operate_upvideo{
    height: 40px;
    background: #F8F8F9;
    border-radius: 12px;
    padding: 0 12px;
    font-size: 14px;
    margin-top: 20px;
}
.operate_upvideo svg{
    cursor: pointer;
}
.operate_btn::before{
    content: "";
    width: 1px;
    height: 12px;
    background: #D7DADE;
    transform: translateY(4px);
    margin: 0 12px;
}
.operate_btn div{
    cursor: pointer;
    margin-right: 16px;
}
.pot_content {
    width: 100%;
    height: 181px;
    background-color: rgba(165, 177, 209, 0.08);
    border-radius: 12px;
    flex-direction: column;
    justify-content: center;
}
.pot_text {
    font-size: 13px;
    color: #25282c;
    line-height: 18px;
    margin-top: 12px;
}
.pot_tips {
    font-size: 13px;
    color: #828b99;
    margin-top: 4px;
    line-height: 18px;
}
.vd_poster {
    width: 42px;
    height: 60px;
    display: block;
    border-radius: 4px;
}
.vd_center {
    margin: 0 16px;
}
.no_name {
    width: 88px;
    height: 24px;
    border: 1px solid #fe6262;
    border-radius: 2px;
    justify-content: center;
    font-size: 13px;
    color: #fe6262;
    cursor: pointer;
}
.hover_edit {
    visibility: hidden;
    cursor: pointer;
}
.cell_edit:hover .hover_edit{
    visibility: visible;
}
</style>
<style>
/* 隐藏 number input 的微调器 */  
input[type=number]::-webkit-inner-spin-button,   
input[type=number]::-webkit-outer-spin-button {   
    -webkit-appearance: none;   
    margin: 0;   
}  
  
/* Firefox 浏览器 */  
input[type=number] {  
    -moz-appearance: textfield;  
}
.video_loader .el-upload {
    display: block;
}
.video_loader .el-upload-dragger {
    width: 100%;
    border: 0;
}
</style>


